<?php

namespace App\Http\Controllers\Api;

use App\Models\Shop\Account;
use App\Models\Shop\Address;
use App\Models\Shop\Cart;
use App\Models\Shop\Order;
use App\Models\Shop\Product;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;

class OrderController extends Controller
{
   /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
   public function index(Request $request)
   {
      $user = JWTAuth::parseToken()->authenticate();  //取其id为$user->id
      $where = function ($query) use ($request, $user) {
         $query->where('user_id', $user->id);
         switch ($request->status) {
            case '' :
               break;
            case 0 :
               $query->where('status', 0);
               break;
            case 1:
               $query->whereIn('status', [1, 2, 3]);
               break;
            case 4:
               $query->where('status', 4);
               break;
         }
      };

      $order_status = config('admin.order_status');
      $orders = Order::with('address', 'user', 'order_products.product')
         ->where($where)
         ->orderByDesc('created_at')
         ->get();

      //统计订单商品数量
      foreach ($orders as $key => $value) {
         foreach ($value['order_products'] as $k => $v) {
            $orders[$key]['total_num'] += $v['num'];
         }
      }

      return response()->json(compact('orders', 'order_status'));
   }

   /**
    * Show the form for editing the specified resource.
    * 结算
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function checkout(Request $request)
   {
      $user = JWTAuth::parseToken()->authenticate();  //取其id为$user->id
      $customer = DB::table('users')->where('id', $user->id)->first();  //用户信息
      $address = DB::table('addresses')->where('user_id', $customer->id)->where('id', $customer->address_id)->first();
      $xing = substr($address['tel'], 3, 4);  //获取手机号中间四位
      $address['tel'] = str_replace($xing, '****', $address['tel']);
      $orders = Cart::all_carts();
      //优惠券
      $accounts = Account::with(['tickets' => function ($query) {
         $query->where('status', 1);
      }])->where('user_id', $user->id)->first();
      //判断优惠券是否过期
      foreach ($accounts['tickets'] as $ticket) {
         if ($ticket->valid_end_time <= Carbon::now()) {
            DB::table('tickets')->where('id', $ticket['id'])->update(['status' => 2]);
         }
         //查出可用优惠券
         if ($orders['product_num']['total_price'] >= $ticket->with_amount) {
            $tickets = $accounts['tickets'];
         }
      }

      return response()->json(compact('orders', 'address', 'tickets'));
   }

   /**
    * Store a newly created resource in storage.
    * 下单
    * @param \Illuminate\Http\Request $request
    * @return \Illuminate\Http\Response
    */
   public function store(Request $request)
   {
      $user = JWTAuth::parseToken()->authenticate();  //取其id为$user->id
      $data = Cart::all_carts();
      $total_price = $data['product_num']['total_price']; //总价
      //优惠金额
      $account = Account::with(['tickets' => function ($query) use ($request) {
         $query->where('id', $request->ticket_id);
         $query->where('status', 1);
         $query->select('used_amount');
      }])->where('user_id', $user->id)->first();

      DB::beginTransaction();
      try {
         //生成订单
         $order = Order::create([
            'order_code' => make_order_code(), //订单号
            'user_id' => $user->id,
            'status' => 0, //订单状态
            'total_price' => $total_price, //总金额
            'free_price' => $account['tickets'][0]['used_amount'],  //优惠金额
            'pay_price' => ($total_price - $account['tickets'][0]['used_amount']) //实付金额
         ]);
         //订单地址
         $address = Address::find($request->address_id);
         $order->address()->create([
            'province' => $address['province'],
            'city' => $address['city'],
            'area' => $address['area'],
            'detail' => $address['detail'],
            'name' => $address['name'],
            'tel' => $address['tel']
         ]);

         $carts = $data['carts'];
         foreach ($carts as $cart) {
            //判断库存是否足够
            if ($cart->product->stock != '-1' and $cart->product->stock - $cart->num < 0) {
               $info = ['status' => 0, 'msg' => '商品' . $cart->product->name . ', 目前仅剩下' . $cart->product->stock . ' 件. \n请返回购物车, 修改订单后再下单!'];
               return response()->json($info);
            }
            //削减库存数量
            if ($cart->product->stock != '-1') {
               $cart->product->decrement('stock', $cart->num);
            }
            //插入订单商品表
            $order->order_products()->create([
               'product_id' => $cart->product_id,
               'num' => $cart->num
            ]);
         }
         //删除已使用优惠券
         DB::table('account_tickets')->where('account_id', $account['id'])->where('ticket_id', $request->ticket_id)->delete();
         //清空购物车
         Cart::where('user_id', $user->id)->delete();
      } catch (\Exception $e) {
         DB::rollBack();
         $info = ['status' => 0, 'msg' => $e->getMessage()];
         return response()->json($info);
      }
      DB::commit();
      $info = ['status' => 1, 'msg' => $order->id];
      return response()->json($info);
   }

   /**
    * Display the specified resource.
    * 查看订单
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function show($id)
   {
      $order = Order::with('address', 'express', 'user', 'order_products.product')->find($id);
      $order_status = config('admin.order_status');
      return response()->json(compact('order', 'order_status'));
   }

   /**
    * Remove the specified resource from storage.
    * 取消订单
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function destroy($id)
   {
      //查出对应商品，库存还回去
      $order = Order::with('order_products')->find($id);
      foreach ($order->order_products as $item) {
         $product = Product::find($item->product_id);
         //如果不是无限库存
         if ($product->stock != -1) {
            $product->increment('stock', $item->num);
         }
      }
      DB::table('order_products')->where('order_id', $id)->delete();  //删除订单商品
      DB::table('order_addresses')->where('order_id', $id)->delete();  //删除订单地址
      Order::destroy($id);  //删除订单表
   }
}
